#ifndef __OUTPUT_CPP__
#define __OUTPUT_CPP__

#include "env.h"
#include "bytearrays.h"
#include "output.h"
#include <dirent.h>
#include <unistd.h>

namespace WServer {

namespace Output {

int logOutfile[3], logNum[3], logRows[3];
pthread_mutex_t logThreadMutex[3];
const char* logname[3] = {"log", "err", "msg"};

void createLogFile(int index)
{
	if (GData::outputfile == 1) {
		char filename[256];
		logNum[index]++;
		logRows[index] = 0;
		sprintf(filename, "%s_%s_%d.txt", logname[index], GData::modulelist[GData::moduleindex].modulename.c_str(), logNum[index]);
		logOutfile[index] = open(filename, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
		if (logOutfile[index] == 0) {
			exit(-1);
		}
	}
}

void wserInitOutput()
{
	logOutfile[0] = logOutfile[1] = logOutfile[2] = 0;
	logNum[0] = logNum[1] = logNum[2] = 0;
	logRows[0] = logRows[1] = logRows[2] = 0;

	pthread_mutex_init(&logThreadMutex[0], 0);
	pthread_mutex_init(&logThreadMutex[1], 0);
	pthread_mutex_init(&logThreadMutex[2], 0);
	createLogFile(0);
	createLogFile(1);
	createLogFile(2);
}

void __wserPrintMsg(int index, const char* format, ...)
{
	char logLine[MAX_SIZE];
	va_list arg_ptr;
	va_start(arg_ptr, format);

	vsprintf(logLine, format, arg_ptr);

	if (GData::outputfile == 1) {
		pthread_mutex_lock(&logThreadMutex[index]);
		__rwsize = write(logOutfile[index], logLine, strlen(logLine));
		logRows[index]++;
		if (logRows[index] > GData::logMaxRows) {
			close(logOutfile[index]);
			createLogFile(index);
		}
		pthread_mutex_unlock(&logThreadMutex[index]);
	}

	if (GData::outputconsole == 1) {
		printf("%s", logLine);
	}
	va_end(arg_ptr);
}

void wserUninitOutput()
{
	if (GData::outputfile == 1) {
		close(logOutfile[0]);
		close(logOutfile[1]);
		close(logOutfile[2]);
		pthread_mutex_destroy(&logThreadMutex[0]);
		pthread_mutex_destroy(&logThreadMutex[1]);
		pthread_mutex_destroy(&logThreadMutex[2]);
	}
}

} //namespace Output

} //namespace WServer
#endif //__OUTPUT_CPP__
